<template>
  <div>
    <el-dialog :before-close="handleClose" :title="title" :visible.sync="isOpen" width="900px"
               :close-on-click-modal="false"
               destroy-on-close>
      <el-form :model="form" :rules="dialogRules"
               ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="方案名称" prop="strategyName">
              <el-input style="width: 600px" v-model="form.strategyName" @input="$forceUpdate()"
                        placeholder="请输入方案名称" :min="2" :max="64"></el-input>
            </el-form-item>
            <el-form-item label="方案类型" prop="mediaType">
              <el-select v-model="form.mediaType" placeholder="请选择方案类型">
                <el-option label="图片" :value="1"/>
                <el-option label="网页" :value="2"/>
                <!--<el-option label="视频" :value="3"/>-->
              </el-select>
            </el-form-item>
            <el-form-item label="设备区域" prop="areaIds" v-if="false">
              <el-tree-select
                v-model="form.areaIds"
                :data="dataTree"
                :render-after-expand="false"
                placeholder="请选择设备区域"
                show-checkbox
                check-strictly
                multiple
                @change="handleAreaChange"
              />
              <span style="margin-left: 10px;cursor: pointer;color: #3571FF;font-size: 12px"
                    @click="toggleDeviceVisible">{{ isShowDevice ? '隐藏设备' : '显示设备' }}</span>
            </el-form-item>
            <el-form-item label="设备" prop="deviceIdList" v-if="isShowDevice">
              <el-select
                multiple
                clearable
                filterable
                v-model="form.deviceIdList"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in deviceList"
                  :key="item.value"
                  :label="item.deviceName"
                  :value="item.deviceId"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.mediaType==2" label="网址" prop="webpageAddress">
              <el-input style="width: 600px" v-model="form.webpageAddress" @input="$forceUpdate()"
                        placeholder="请输入网址"/>
            </el-form-item>
            <!--图片上传-->
            <el-form-item v-if="form.mediaType==1" label="图片" prop="imageFileList">
              <el-upload
                accept=".png,.jpg,.jpeg,.bmp"
                :auto-upload="false"
                action=""
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="form.imageFileList"
                :on-change="handleUploadChange"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">目前支持 .png .jpg .jpeg等格式 , <span style="color: #FB0505">文件名不能包含中文</span>
                </div>
              </el-upload>
            </el-form-item>
            <!--视频上传-->
            <el-form-item v-if="form.mediaType==3" label="视频" prop="videoFileList">
              <el-upload
                ref="uploadRef"
                :auto-upload="false"
                accept=".avi,.mp4,.wmv"
                :multiple="true"
                :file-list="videoFileList"
                :limit="limit"
                class="upload-demo"
                drag
                action=""
                :on-change="handleUploadChange"
                :on-remove="handleRemove"
                :on-exceed="onExceed"
                :show-file-list="true"
              >
                <el-icon class="el-icon--upload">
                  <img :src="IconXls1" v-if="IconXls1" alt=""/>
                  <upload-filled v-else/>
                </el-icon>
                <div class="el-upload__text">将文件拖至这里或<em> 点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持.mp4,.avi文件,单个文件不超过 500MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="form.mediaType==1" label="间隔时间" prop="intervalTime">
              <div style="display: flex;flex-direction: row">
                <el-input-number style="width: 600px" v-model="form.intervalTime" @input="$forceUpdate()" :min="0"
                                 :max="3600"/>
                <div style="margin-left: 10px">s [0-3600]</div>
              </div>
            </el-form-item>
            <el-form-item v-if="form.mediaType==1" label="播放模式" prop="playbackMode">
              <el-select v-model="form.playbackMode" placeholder="请选择播放模式">
                <el-option label="顺序" value="1"/>
                <el-option label="随机" value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="isSureDisable&&title!==`编辑`" @click="ok()">确 定</el-button>
          <el-button plain @click="handleClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--图片预览-->
    <el-dialog :visible.sync="dialogVisible">
      <el-image w-full :src="dialogImageUrl" fit="contain" alt="Preview Image"/>
    </el-dialog>
  </div>
</template>

<script>
// import {queryDeviceInfo} from "@/api/record";
// import {getAreaTreeAllApi} from "@/api/device";
import {addMedia, mediaImageUpload, updateMedia} from "@/api/media-services";
import {fileUploadApi} from "@/api/community/person";

export default {
  mounted() {
    // this.getAreaTreeAll()

  },
  data() {
    var check_intervalTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('间隔时间不能为空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        if (value > 3600) {
          callback(new Error('间隔时间必须是0~3600s之间'));
        } else if (value < 0) {
          callback(new Error('间隔时间必须是0~3600s之间'));
        } else {
          callback();
        }
      }
    };
    return {
      isSureDisable: true,
      dataList: [], isOpen: false, title: "", disabled: "",
      form: {
        strategyName: "",
        intervalTime: 5,
        mediaType: 1,
        playbackMode: "1",
        deviceIdList: [],
        webpageAddress: "",
        imageFileList: [
          // {
          //   name: 'food.jpeg',
          //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
          // },
        ]
      },
      dialogFormLabelPosition: 'right',
      dataTree: [],
      deviceList: [],
      IconXls1: [],
      limit: 10,
      dialogRules: {
        strategyName: [
          {required: true, message: '必须填入方案名称', trigger: 'blur'},
          {min: 2, max: 64, message: "方案名称长度必须介于 2 和 64 之间", trigger: "blur",},
        ],
        mediaType: [
          {required: true, message: '必须媒体类型', trigger: 'blur'},
        ],
        areaIds: [
          {required: true, message: '必须选择区域', trigger: 'blur'},
        ],
        webpageAddress: [
          {required: true, message: '必须输入网址', trigger: 'blur'},
        ],
        intervalTime: [
          {required: true, message: '必须输入间隔', trigger: 'blur'},
          // {validator: check_intervalTime, trigger: 'blur'},
        ],
        playbackMode: [
          {required: true, message: '必须输入播放模式', trigger: 'blur'},
        ],
        // imageFileList: [
        //   {required: true, message: '必须上传图片', trigger: 'blur'},
        // ],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      videoFileList: [
        // {
        //   name: 'food.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        // },
      ],
      imageUploadContainer: [],
      videoUploadContainer: [],
      isShowDevice: '',
    }
  },
  methods: {

    //el-upload/change变动
    handleUploadChange(current, group) {
      console.log(this.form.imageFileList.length)
      const upload_data = new FormData();
      switch (this.form.mediaType.toString()) {
        //image
        case'1' :
          if (current.raw.type.indexOf('image') != -1 && current.raw.name.indexOf('bmp') == -1 && !(/[\u4E00-\u9FA5]+/g.test(current.name))) {
            // console.log('RW', /[\u4E00-\u9FA5]+/g.test(current.name))
            if (current.raw.size <= 5 * 1 * 1048576) {
              upload_data.append("fileData", current.raw);
              upload_data.append("fileType", '1');
              fileUploadApi(upload_data).then(res => {
                if (res) {
                  this.imageUploadContainer.push(res.path)
                  if (this.title == '添加') {
                    this.form.imageFileList.push({name: res.path.substring(56).trim(), url: res.path})
                  }
                  this.isSureDisable = false
                } else {
                  this.$message({message: '连接出现问题，请稍后再试', type: "error"});
                  // this.isOpen = false
                  this.isSureDisable = false
                }
              })

            } else {
              this.$message({message: '文件大小不能超过5M', type: "warning"});
              return false;
            }
          } else {
            console.log(this.form.imageFileList);
            setTimeout(() => {
              this.$nextTick(() => {
                this.form.imageFileList = group.pop()
              })
            }, 500)
            this.$message({
              message: '目前仅支持 .png .jpg .jpeg  格式且文件名不含中文，请删除后重新上传 !',
              type: "warning"
            });
            return false
          }
          break;
        //video
        case' 3':
          if (current.raw.type.indexOf('video') != -1) {
            if (current.raw.size <= 500 * 1 * 1048576) {
              upload_data.append("file", current.raw);
              upload_data.append("type", '2');
              this.mediaImageUpload(upload_data).then(res => {
                this.imageUploadContainer.push(res.data)
              })
            } else {
              this.msgWarning('文件大小不能超过500M！')
              return false;
            }
          } else {
            setTimeout(() => {
              this.videoFileList.pop()
            }, 500)
            this.msgWarning('目前仅支持 .avi .mp4 .wmv  格式，请重新上传 !')
            return false
          }
          break;
      }
    },

    //删除图片
    handleRemove(uploadFile, uploadFiles) {
      let find_index = ''
      switch (this.form.mediaType.toString()) {
        case '1':
          find_index = this.form.imageFileList.map(i => i.name).indexOf(uploadFile.name);

          if (find_index > -1) {
            this.form.imageFileList.splice(find_index, 1);
            this.$forceUpdate();
          }
          if (this.imageUploadContainer.length) {
            this.imageUploadContainer.splice(find_index, 1)
            this.$forceUpdate();
          }
          break;
      }
    },
    //预览图片
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url
      this.dialogVisible = true
    },

    handleAreaChange() {
      this.getDeviceList(this.form.deviceIds)
    },

    toggleDeviceVisible() {
      this.isShowDevice = !(this.isShowDevice)
    },
    //数组去重
    unique(arr) {
      // console.log( Array.from(new Set(arr)))
      return Array.from(new Set(arr))
    },
    // //获取设备下拉列表
    // getDeviceList(deviceIds) {
    //   this.form.deviceIdList = []
    //   queryDeviceInfo(this.form).then(res => {
    //     // console.log(form,res)
    //     this.deviceList = res.data
    //     const deviceIds = []
    //     res.data.forEach((element, index) => {
    //       // console.log(element);
    //       deviceIds.push(element.deviceId)
    //     })
    //     // console.log(unique(deviceIds))
    //     // console.log(11111)
    //     this.form.deviceIdList = this.unique(deviceIds)
    //     if (this.form.areaIds.length == 0) {
    //       // console.log(22222)
    //       this.form.deviceIdList = []
    //     }
    //     // console.log(333333)
    //   })
    // },
    // getAreaTreeAll() {
    //   getAreaTreeAllApi({}).then((res) => {
    //     this.dataTree = res.data;
    //     recursionDataTree(this.dataTree);
    //     // console.log('data-tree', dataTree);
    //   });
    //   this.getDeviceList()
    // },
    // 重置
    reset() {
      // console.log('reset')
      //reset得复制不然下一次打开的时候，就会校验失败
      // https://blog.csdn.net/weixin_43216105/article/details/97394440
      this.form = {
        strategyName: "",
        mediaType: 1,
        webpageAddress: "",
        playbackMode: "1",
        deviceIdList: undefined,
        intervalTime: 5,

      }
      this.form.imageFileList = []
      this.imageUploadContainer = []
      this.videoUploadContainer = []
    },

// 弹窗关闭处理方法 && 取消
    handleClose() {
      this.isOpen = !(this.isOpen)
      this.reset()
    },

    open(type, arr) {
      this.isOpen = true;
      this.title = type
      if (type == '添加') {
        this.reset()
      } else {
        let areaIds = []
        let deviceIds = []
        //用于图片展示
        if (arr.lookPictureAddress != null && arr.lookPictureAddress != '') {
          let imgArray = arr.lookPictureAddress.split(',')
          let temp = []
          imgArray.forEach((current, index) => {
            temp.push({
              name: current,
              url: `${process.env.VUE_APP_BASE_URL}${current}`,
            })
            this.$nextTick(() => {
              this.$forceUpdate()
              this.form.imageFileList = temp
            })
          })
        }
        //用于图片上传
        if (arr.pictureAddress != null && arr.pictureAddress != '') {
          let uploadImgArray = arr.pictureAddress.split(',')
          uploadImgArray.forEach((current, index) => {
            this.imageUploadContainer.push(current)
          })
        }
        //用于视频上传
        if (arr.videoAddress != null && arr.videoAddress != '') {
          let uploadVideoArray = arr.videoAddress.split(',')
          uploadVideoArray.forEach((current, index) => {
            this.videoUploadContainer.push(current)
          })
        }
        // arr.areaInfo.forEach((item, index) => {
        //   areaIds.push(item.areaId)
        // })
        // arr.deviceInfo.forEach((item, index) => {
        //   deviceIds.push(item.deviceId)
        // })
        this.form.strategyName = arr.strategyName
        this.form.mediaId = arr.mediaId
        this.form.mediaType = arr.mediaType
        this.form.areaIds = areaIds
        this.form.deviceIds = deviceIds
        this.form.intervalTime = arr.intervalTime
        this.form.playbackMode = arr.playbackMode
        this.form.webpageAddress = arr.webpageAddress
        // this.$forceUpdate();
        this.$nextTick(() => this.$refs.formRef.clearValidate())
      }
    },

    //表单提交
    ok() {
      console.log('submit', this.form)
      this.$refs.formRef.validate((validate, fields) => {
        if (validate) {
          let params = {...this.form}
          delete params.deviceIds
          params.deviceIdList = this.form.deviceIds
          // console.log('params', imageUploadContainer)
          // console.log(this.imageUploadContainer.join(','), 'p')
          params.pictureAddress = this.imageUploadContainer.join(',')
          params.videoAddress = this.videoUploadContainer.join(',')

          switch (this.title) {
            case '添加':
              addMedia(params).then((res) => {
                console.log('res,方案名称', res);
                if (res) {
                  this.msgSuccess('添加成功')
                  this.handleClose()
                  setTimeout(() => {
                    this.$emit('getList')
                  }, 1000)
                this.isSureDisable = true
                }
              }).catch(e => {
                console.log(e);
              })
              break;
            case '编辑':
              // console.log('params', params)
              // return false
              updateMedia(params).then((res) => {
                // console.log(res);
                if (res) {
                  this.msgSuccess('修改成功')
                  this.handleClose()
                  setTimeout(() => {
                    this.$emit('getList')
                  }, 1000)
                  this.isSureDisable = true
                }
              }).catch(e => {
                console.log(e);
              })
              break;
          }

        } else {
          console.log('error submitForm', fields);
        }
      });
    },

    onExceed() {
      this.msgWarning(`最多只能上传 ${this.limit}个文件！`);
    },


    // 递归树
//     recursionDataTree(treeList) {
//       this.treeList.forEach((item, index) => {
//         item.value = item.areaId;
//         item.label = item.areaName;
//         if (item.children.length !== 0) {
//           this.recursionDataTree(item.children);
//         }
//       });
//     }
  },
  //
  // watch:{
  //   "form.imageFileList":{
  //     handler:function (val,oldVal) {
  //       console.log('watch 1', 'newval: ', val, '   oldVal:', oldVal)
  //     }
  //   }
  // },


}
</script>

